public without sharing class MeasureCalcFillSimpleController {
    
    public Boolean isErr {get;set;}

	public Boolean isSuccess {get;set;}

    public Boolean isSaler {get; private set;}

	public String msg {get;set;}

	public Measure_Calculate__c mc {get;set;}//测算

	public Opportunity opp  {get; private set;}//业务机会

	public Boolean isNew ;//是新建还是编辑

	public  String oppId ; 
	public String mcId ; 
	private String lastMcId ; 

    public Boolean isDealer {get; private set;}
	public String  company {get;private set;}
	public String backId {get;private set;}
 	
 	public String cate1combox {get; private set;}

 	public String cate2combox {get; private set;}

 	public String brandcombox {get; private set;}


	public User u ; 

	public String paramJson {get; private set;}

	public String saveJson {get;  set;}

    public String resJson {get; set;}

    public Integer mcRight {get; private set;}

    public String accMapJson {get;private set;}

    public Boolean isNeedSelectAccount {get ;private set;} //是否需要选择 报价适用 的终端客户

	public class ControllerException extends Exception {}
    public MeasureCalcFillSimpleController() {}

    public MeasureCalcFillSimpleController(ApexPages.StandardController con) {}
    public void init(){

    	mc = new Measure_Calculate__c();
        backId =System.currentPageReference().getParameters().get('id');

        if(backId == null )backId =System.currentPageReference().getParameters().get('mid');

        isNew = false;


        u = [select Id ,Profile.Name,SubCompany__c from User where Id=:UserInfo.getUserId()];

    	 Boolean isSuperEdit = u.Profile.Name == '系统管理员' || u.Profile.Name == '财务部总监' || u.Profile.Name == '财务部主管' ;
            
         Boolean isResultPage =  URL.getCurrentRequestUrl().toExternalForm().toLowerCase().contains('measurecalcresult') ;
       
        isSaler = u.Profile.Name == '销售部分销销售员' || u.Profile.Name == '销售部直销销售员';
       
    	try {
            if(backId == null ) setErr('页面打开错误!');
    	    if(Id.valueOf(backId).getSObjectType() == Measure_Calculate__c.SObjectType ){
                mcId = backId;
	    		mc = getMeasureCalc(mcId);
	    		if(!isResultPage && (  mc.Status__c == '审批成功' || ( mc.Status__c == '已提交' && (!isSuperEdit &&  isSaler))  ) )setErr('已提交或审批成功不能修改!');
                opp  = [select Id,RecordType.DeveloperName,StageName,Account.Name, Account.Level__c ,Account.LISRevenue__c from Opportunity where Id=:mc.Opportunity__c];

	    	}else if(Id.valueOf(backId).getSObjectType() == Opportunity.SObjectType ){
                oppId = backId;				 
                opp  = [select Id,RecordType.DeveloperName,StageName,Account.Name, AccountId,Account.Level__c ,Account.LISRevenue__c from Opportunity where Id=:oppId];
	    	      if(opp.StageName == '合同签订' || opp.StageName == '失败' )setErr('业务机会'+opp.StageName +'阶段不能操作!');

	            isNew = true;
	            lastMcId = getLastMeasureCalc(oppId);
	            if(lastmcid != null){
	                mc = getMeasureCalc(lastMcId).clone();
	                mc.LastMeasureCalc__c = lastMcId;
                    mc.IsActive__c = false;
	            }
	    		mc.Opportunity__c = opp.Id;
	    		mc.Company__c = u.SubCompany__c ; 
	    		mc.Status__c = '草案中';
                mc.CoopDealer__c =  opp.RecordType.DeveloperName == 'DealerOpportunity' ?  opp.AccountId : null ;
	            mc.Id = null;
                mc.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('SimpleCalculation', 'Measure_Calculate__c');

	    	}else{
	    		setErr('页面打开错误!');

	    	}
            //是否需要选择适用客户
            isNeedSelectAccount = (opp.RecordType.DeveloperName == 'DealerOpportunity') ? true  : false  ;
            //设置终端客户
            if(!isNeedSelectAccount){
                 mc.TerminalName__c = opp.AccountId ; 
                 mc.CoopDealer__c = null;
            }else{
                mc.CoopDealer__c = opp.AccountId;
            }
            getIntentTerinalAccount();

            mcRight = MeasureRightUtil.getRight(mc.Company__c);
            System.debug('mcRight==>'+mcRight);
	    	company = mc.Company__c;
        	cate1combox = getOptsFromProduct('Classify1__c');
        	cate2combox = getCate2();
        	brandcombox = getOptMap(ImportObject.getPicklistValues('Measure_Calculate_Product__c', 'ProductBrand__c', false));
    	}catch (Exception e) {
			isErr = true;
    	    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	}
    	


    }

    public void setNil(){
    	paramJson = '[]';
    	saveJson = '[]';
        accMapJson = '{}';
    	msg = '';
    }
    public String getOptMap(Map<String,String> opts){
        System.debug('getOptMap');
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', '120');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }
    public static String  getCate2(){
    	 Map<String,List<Map<String,String>>> cate2Map = new Map<String,List<Map<String,String>>>();
        for(AggregateResult arg: [select Classify1__c,Classify2__c   from ProductStructure__c where Classify1__c != null and Classify3__c ='试剂'   group by Classify1__c ,Classify2__c  ]){
			String cate1 = String.valueOf(arg.get('Classify1__c'));
			String cate2 = String.valueOf(arg.get('Classify2__c'));
			List<Map<String,String>> c2set = new List<Map<String,String>>();
			if(cate2Map.containsKey(cate1)){
				c2set.addAll(cate2Map.get(cate1));
			}
			 Map<String ,String> dataMap = new Map<String,String>();
        	dataMap.put('label',cate2 );
        	dataMap.put('value',cate2 );
			c2set.add(dataMap);
			cate2Map.put(cate1, c2set);

		}
        return EncodingUtil.urlEncode(JSON.serialize(cate2Map), 'UTF-8');
    }

    private void getIntentTerinalAccount(){
       Map<String,String> accMap = new Map<String,String>();

        for(IntentProduct__c ip : [select TerminalClient__c,TerminalClient__r.Name from IntentProduct__c where Opportunity__c =:mc.Opportunity__c and TerminalClient__c != null ]){

            accMap.put(ip.TerminalClient__r.Name,ip.TerminalClient__c );
        }
        accMapJson = JSON.serialize(accMap);

    }

    public String getOptsFromProduct(String cate  ){
         List<Map<String,String>>  dList = new List<Map<String,String>>();

        for (AggregateResult arg  :Database.query('select '+cate +'  from ProductStructure__c  where '+cate+' != null  and Classify3__c =\'试剂\' group by '+cate ) ){
           	 Map<String ,String> dataMap = new Map<String,String>();
        	dataMap.put('label',String.valueOf(arg.get(cate)) );
        	dataMap.put('value',String.valueOf(arg.get(cate)) );
        	dList.add(dataMap);
        }
    
        return EncodingUtil.urlEncode(JSON.serialize(dList), 'UTF-8');

    }
    
    private void setErr(String message ){	 
    	isErr  =true;
    	throw new ControllerException(message);

    }
    //获取上次测算的信息 如有审批通过的 则取审批通过的 没有审批通过的则 按时间取最新的
    public String getLastMeasureCalc(String opid){
        List<Measure_Calculate__c>  mList = new List<Measure_Calculate__c> ();
        mList = [select Id from  Measure_Calculate__c where Opportunity__c =:opid  and RecordType.DeveloperName ='SimpleCalculation' and Status__c = '审批成功' Order by  CreatedDate desc ];
        if(mList.size() > 0) return mList[0].Id;
        return null;
    }

     //获取测算信息
    private Measure_Calculate__c getMeasureCalc(String mid ){
    	 Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
            sql += ',Opportunity__r.Account.Name,Opportunity__r.Account.Level__c,Opportunity__r.Account.LISRevenue__c,CoopDealer__r.Name ';
            sql += ',TerminalName__r.Name , TerminalName__r.Level__c,TerminalName__r.LISRevenue__c ';
            sql += ' from Measure_Calculate__c where Id = \'' + mid + '\'';
           List<Measure_Calculate__c> mcList = Database.query(sql);
           if(mcList == null || mcList.size() == 0)return null;
           return mcList[0];

    }


    public void getDetails(){
   
   		if(mcId != null){
   			paramJson = getDetails(mcId);
   		}else if(lastMcId != null ){
            paramJson = getDetails(lastMcId);
        }
   
    }
    public String getDetails(String mid ){


        String sql = 'select Id , ProfessionalGroupIncome__c,GrossProfitRate__c ,ProductClass2__c,ProductClass1__c ,ProductBrand__c,EstimatedSales__c '+
        ' from Measure_Calculate_Product__c where Measure_Calculate__c = \'' + mid + '\' and IsEquipRelated__c != true ';
    
    	List<Measure_Calculate_ProductBean> tmpList = new List<Measure_Calculate_ProductBean>();
       for(Measure_Calculate_Product__c mcp : Database.query(sql)){
       		tmpList.add(new Measure_Calculate_ProductBean(mcp));
       }
       return EncodingUtil.urlEncode(JSON.serialize(tmpList), 'UTF-8');


    }

   


    public void save1(){
            System.debug(saveJson);

    	msg = '';
        
        //判断整体打包

        
        List<Measure_Calculate_Product__c> mcpList = new List<Measure_Calculate_Product__c>();

        try {

           Account acc =  [select Id,Level__c  from Account where Id=:mc.TerminalName__c ];
           
             Map<String ,Object> res = ( Map<String ,Object> ) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
             List<Object> resList =( List<Object> )res.get('data');
             Set<String> proLineSet = new Set<String>();
             Set<String>  ljset = new Set<String>{'血型','血液','体液'};
            for (Object o  : resList) {
                Map<String,Object> mo = (Map<String,Object>) o;
                Measure_Calculate_Product__c mcp = new Measure_Calculate_Product__c();
                mcp.ProductClass1__c = String.valueOf(mo.get('cate1'));
                mcp.ProductClass2__c = String.valueOf(mo.get('cate2'));
                mcp.ProductBrand__c = String.valueOf(mo.get('brand'));
                mcp.GrossProfitRate__c = getDecimalValue(mo.get('subgross'));
                mcp.EstimatedSales__c = getDecimalValue(mo.get('estimatedSales'));
                mcp.ProfessionalGroupIncome__c = getDecimalValue(mo.get('proincome'));
                mcpList.add(mcp);
                proLineSet.add( ljset.contains(mcp.ProductClass1__c) ? '临检' : mcp.ProductClass1__c);
                

            }


            if(acc.Level__c != null && acc.Level__c.contains('三级') ){
                if(!proLineSet.containsAll(new Set<String>{'免疫','分子','微生物','生化','临检'}) ){
                    msg = '不满足整体打包条件!<br/>整体打包：<br/>三级以上医院5个及5个以上产品线，二级以上医院4及4个以上产品线；产品线包含：生化、免疫、临检（血液、血型、体液)、微生物、分子。';
                    return;
                }
            }else{
               if(!proLineSet.containsAll(new Set<String>{'免疫','微生物','生化','临检'})  ){
                    msg = '不满足整体打包条件!<br/>整体打包：<br/>三级以上医院5个及5个以上产品线，二级以上医院4及4个以上产品线；产品线包含：生化、免疫、临检（血液、血型、体液)、微生物、分子。';
                    return;
                } 
            }
            Map<String ,Object> resMap = ( Map<String ,Object> )  res.get('calc');
            mc.MaccuraYieldNow__c = getDecimalValue(resMap.get('groupProfit'));
            mc.CompanyYieldNow__c = getDecimalValue(resMap.get('subProfit'));
            mc.MaccuraIncomeNow__c = getDecimalValue(resMap.get('groupIncome'));
            mc.CompanyIncomeNow__c = getDecimalValue(resMap.get('subIncome'));
            mc.MaccuraSalesNow__c = getDecimalValue(resMap.get('groupSale'));
            mc.CompanySalesNow__c = getDecimalValue(resMap.get('subSale'));
        
            
        }catch (Exception e) {
            System.debug('MeasureCalcFillSimpleController'+ e.getMessage()+e.getStackTraceString());
             msg = '保存失败!'+e.getMessage();
             return;

        }
        
    	

    	SavePoint sp = Database.setSavepoint();
    	try {
    	    upsert mc;
            if(!isNew){
                
                List<Measure_Calculate_Product__c> tL =  [select Id from Measure_Calculate_Product__c where Measure_Calculate__c =:mc.Id ];
                if(tL.size() > 0)delete tL;
            }

    	    for (Measure_Calculate_Product__c mcp :mcpList ) {
    	    	mcp.Measure_Calculate__c = mc.Id ; 

    	    }
    	    if(mcpList.size() > 0 ) insert mcpList;
    	    msg = '保存成功!';
            backId = mc.Id ; 
    		isSuccess = true;

    	}catch (Exception e) {
    		if(isNew){
                mc.Id = null; 
                backId = oppId;
            }

    	    msg = '保存失败!'+e.getMessage();
    	    Database.rollback(sp);
    	}
    	

    }
    private Decimal getDecimalValue(Object o ){
    	if(o == null)return null;
    	String s = String.valueOf(o).trim();
    	if(s=='') return null; 
    	return Decimal.valueOf(s);
    }

    public class Measure_Calculate_ProductBean{
     
    	public String cate1 {get;set;}//一级分类
    	public String cate2 {get;set;}//二级分类
    	public String brand {get;set;}//品牌
    	public Decimal proincome {get;set;}//专业组年收入
    	public Decimal subgross {get;set;}//子公司毛利

    	public Decimal estimatedSales {get;set;}//预计销售
        public Measure_Calculate_ProductBean(){}
    	public Measure_Calculate_ProductBean( Measure_Calculate_Product__c mcp ){
    		proincome = mcp.ProfessionalGroupIncome__c;
    		subgross = mcp.GrossProfitRate__c ; 
    		cate1 = mcp.ProductClass1__c;
    		cate2 = mcp.ProductClass2__c;
    		brand = mcp.ProductBrand__c;
    		estimatedSales = mcp.EstimatedSales__c;

    	}
    	
    }


}